//
//  SSCRequest.m
//  SSC
//
//  Created by 红沙尘 on 17/6/6.
//  Copyright © 2017年 红沙尘. All rights reserved.
//

#import "SSCRequest.h"
#import "AFHTTPSessionManager.h"
#import "HSCLog.h"
#import "SecurityUtil.h"

@implementation SSCRequest

+(void)requestWithApi:(NSString *)url
                param:(NSDictionary *)param
          thenSuccess:(void (^)(NSDictionary *responseObject))success
                 fail:(void (^)(NSError *error))fail
{
    if (url.length == 0) {
        [MTool showMessage:@"地址不能为空" inView:nil];
        return;
    }
    
    NSString *requestUrl = url;
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST"
                                                                                 URLString:requestUrl
                                                                                parameters:nil
                                                                                     error:nil];
    request.timeoutInterval= 600;
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    NSMutableDictionary *args = [self apiparam:param];

    NSString *aesdataresult = [SecurityUtil encryptAESData:[self stringWithDictionary:args]];
    
    // 设置body
    [request setHTTPBody:[aesdataresult dataUsingEncoding:NSUTF8StringEncoding]];
    
    AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];
    responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                 @"text/html",
                                                 @"text/json",
                                                 @"text/javascript",
                                                 @"text/plain",
                                                 nil];
    manager.responseSerializer = responseSerializer;
    
    [[manager dataTaskWithRequest:request
                completionHandler:^(NSURLResponse * _Nonnull response,
                                    id  _Nullable responseObject,
                                    NSError * _Nullable error) {
        
        if (!error) {
            
            NSString *receiveStr = [[NSString alloc] initWithData:responseObject
                                                         encoding:NSUTF8StringEncoding];
            
            NSString *jsonStr = [SecurityUtil decryptAESData:receiveStr];
            
            NSDictionary *dict = [self dictionaryWithJsonString:jsonStr];

//            [HSCLog saveDebugWithURL:url param:args result:dict];
    
            NSLog(@"url  = %@",url);
            NSLog(@"args = %@",args);
            NSLog(@"dict = %@",jsonStr);
            
            if ([dict[@"ret"] intValue] == 1) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    !success ? : success(dict);
                });
            } else {
                
                [MTool showMessage:dict[@"msg"] inView:nil];
                [HSCLog saveDebugWithURL:url param:args result:dict];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    fail(error);
                });
            }
            
        } else {
            NSLog(@"%@",error);
//            [MTool showMessage:error.localizedDescription inView:nil];
            NSDictionary *dict = @{@"desc":[NSString safeString:error.localizedDescription],
                                   @"reason":[NSString safeString:error.localizedFailureReason],
                                   @"code":[NSString stringWithFormat:@"%d",(int)error.code]};

            [HSCLog saveDebugWithURL:url param:args result:dict];

            dispatch_async(dispatch_get_main_queue(), ^{
                fail(error);
            });
        }
    }] resume];
}

/*
 通讯	类型	说明	备注
 ver	String	软件版本号
 deviceid	String	设备编号	没有就每台设备一个uuid
 guid	String	防刷码
 token	String  登录为空
 uid	String	用户id	登录为空
 */

+ (NSMutableDictionary *)apiparam:(NSDictionary *)param {
    
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];//获取项目版本号
    
    NSMutableDictionary *args = @{}.mutableCopy;
    
    args[@"ver"]      = version;
    args[@"deviceid"] = [NSString safeString:[[UIDevice currentDevice] identifierForVendor].UUIDString];
    args[@"guid"]     = [self guid];
    args[@"token"]    = [Userinfo standardUserinfo].token;
    args[@"uid"]      = [Userinfo standardUserinfo].uid;
    
    for (NSString *key in param.allKeys) {
        args[key] = param[key];
    }
    
    return args;
}

//生成规则：获取当前时间戳,随机插诺干个字母，插入字母个数和位置都是随机的

+ (NSString *)guid {
    
    NSMutableString *guid = [NSMutableString stringWithFormat:@"%ld",(long)[[NSDate date] timeIntervalSince1970]];

    //65～90为26个大写英文字母，97～122号为26个小写英文字母
    
    for (int i = 0; i < arc4random()%5 + 3; i ++) {
        [guid insertString:[NSString stringWithFormat:@"%c",arc4random()%25 + 65]
                   atIndex:arc4random()%guid.length];
    }
    
    for (int i = 0; i < arc4random()%5 + 3; i ++) {
        [guid insertString:[NSString stringWithFormat:@"%c",arc4random()%25 + 97]
                   atIndex:arc4random()%guid.length];
    }
    
    return guid;
}

+ (NSString *)stringWithDictionary:(NSDictionary *)dict {

    NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    
    NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    
    if (str.length == 0) str = @"";
    
    return str;
}

+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

@end
